<template>
  <div class="pushmsg-container" v-loading="loading">
    <el-card class="pushmsg-card">
      <div slot="header" class="clearfix">
        <span>消息编辑</span>
      </div>
      <div class="pushmsg-editView">
        <el-form
          class="pushmsg-editLeft"
          label-width="110px"
          :model="pushInfo"
          label-position="top"
        >
          <!-- <el-form-item label="目标平台(必填)">
            <el-checkbox-group v-model="pushInfo.platform">
              <el-checkbox-button
                v-for="item in basePlatform"
                :label="item"
                :key="item"
                @change="platformChange($event, item)"
                >{{ item }}</el-checkbox-button
              >
            </el-checkbox-group>
          </el-form-item> -->
          <el-form-item label="通知标题">
            <el-input
              v-model="pushInfo.title"
              placeholder="请输入通知栏标题"
            ></el-input>
          </el-form-item>
          <el-form-item label="通知内容">
            <el-input
              type="textarea"
              rows="6"
              v-model="pushInfo.content"
              placeholder="请输入推送内容"
            ></el-input>
          </el-form-item>

          <el-form-item label="附加参数" inline-message="true">
            <div class="div-customemsg">
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="custommsgAdd"
                >自定义参数</el-button
              >
              <el-tooltip placement="right-end" id="item-col">
                <div slot="content">
                  此处填写的键值对数据将在用户点击通知后传输给应用客户端，最多添加10组。
                  <br />建议询问业务开发者该字段内容。
                </div>
                <img class="btn-instructions" src="@/assets/img/question.png" />
              </el-tooltip>
            </div>
            <el-row
              :gutter="20"
              v-for="(item, index) in pushInfo.extras"
              :key="index"
              class="row-margin"
              align="middle"
            >
              <el-col :span="8" class="item-col">
                <el-input v-model="item.key" placeholder="请输入参数"></el-input
              ></el-col>
              <el-col :span="8" class="item-col">
                <el-input v-model="item.value" placeholder="输入值"></el-input
              ></el-col>
              <el-col :span="1" class="item-col">
                <img
                  class="btn-delete"
                  src="@/assets/img/sub.png"
                  @click="custommsgSub(index)"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <div>
              <div class="pushmsg-configTitle">Android配置</div>
              <el-form
                class="pushmsg-editLeft"
                label-width="110px"
                :model="pushInfo"
                label-position="top"
              >
                <el-form-item>
                  <label slot="label">
                    <span>自定义声音</span>
                    <el-tooltip class="item" effect="dark" placement="right">
                      <div slot="content" v-html="androidSoundTip"></div>
                      <i class="el-icon-warning-outline"></i>
                    </el-tooltip>
                  </label>
                  <el-input
                    rows="6"
                    v-model="pushInfo.androidConfig.sound"
                    placeholder="请输入自定义声音文件名称"
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
            <div style="marginTop: 20px;">
              <div class="pushmsg-configTitle">iOS配置</div>
              <el-form
                class="pushmsg-editLeft"
                label-width="110px"
                :model="pushInfo"
                label-position="top"
              >
                <el-form-item>
                  <label slot="label">
                    <span>自定义声音</span>
                    <el-tooltip class="item" effect="dark" placement="right">
                      <div slot="content" v-html="iOSSoundTip"></div>
                      <i class="el-icon-warning-outline"></i>
                    </el-tooltip>
                  </label>
                  <el-input
                    rows="6"
                    v-model="pushInfo.iosConfig.sound"
                    placeholder="请输入自定义声音文件名称, 需要带后缀"
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
          </el-form-item>
        </el-form>
        <div class="recommendPage">
          <div class="pushmsg-previewTitleView">
            <span class="pushmsg-previewTitle">预览</span>
            <span class="pushmsg-previewSubTitle"
              >各平台推送送达效果可参考预览图。</span
            >
          </div>
          <swiper
            ref="mySwiper"
            :options="swiperOptions"
            class="pushmsg-swiper"
            @slideChangeTransitionStart="handleClickSlide"
          >
            <swiper-slide
              class="pushmsg-pimgView"
            >
              <img
                class="pushmsg-img"
                src="@/assets/push/icon-push-android.jpg"
              />
              <span class="pushmsg-appNameAndroid">{{ appName }}</span>
              <span class="pushmsg-msgTitleAndroid">{{ pushInfo.title }}</span>
              <span class="pushmsg-msgInfoAndroid">{{ pushInfo.content }}</span>
            </swiper-slide>
            <swiper-slide
              class="pushmsg-pimgView"
            >
              <img class="pushmsg-img" src="@/assets/push/icon-push-ios.jpg" />
              <span class="pushmsg-appNameiOS1">{{ appName }}</span>
              <span class="pushmsg-msgTitleiOS1">{{ pushInfo.title }}</span>
              <span class="pushmsg-msgInfoiOS1">{{ pushInfo.content }}</span>
            </swiper-slide>
            <swiper-slide
              class="pushmsg-pimgView"
            >
              <img class="pushmsg-img" src="@/assets/push/icon-push-ios2.jpg" />
              <span class="pushmsg-appNameiOS2">{{ appName }}</span>
              <span class="pushmsg-msgTitleiOS2">{{ pushInfo.title }}</span>
              <span class="pushmsg-msgInfoiOS2">{{ pushInfo.content }}</span>
            </swiper-slide>
            <div class="swiper-pagination" slot="pagination"></div>
            <div class="swiper-button-prev" slot="button-prev"></div>
            <div class="swiper-button-next" slot="button-next"></div>
          </swiper>
        </div>
      </div>
    </el-card>
    <el-card class="pushmsg-card">
      <div slot="header" class="clearfix">
        <span>目标人群</span>
      </div>
      <div class="targetIccIdInput">
        <el-form label-width="110px" :model="pushInfo" label-position="top">
          <el-form-item label="选择目标">
            <el-radio-group v-model="pushInfo.target">
              <el-radio :label="1">广播所有人</el-radio>
              <!-- <el-radio :label="2">设备标签(Tag)</el-radio>
              <el-radio :label="3">设备别名(Alias)</el-radio> -->
              <el-radio :label="4">设备ID</el-radio>
              <!-- <el-radio :label="5">用户分群推送</el-radio> -->
            </el-radio-group>
          </el-form-item>
        </el-form>
        <el-input
          v-model="registrationID"
          placeholder="添加设备ID，并按Enter键结束"
          @keyup.enter.native="submitRegId()"
          v-if="pushInfo.target == 4"
        ></el-input>
        <div class="regIdsView" v-if="pushInfo.target == 4">
          <el-tag
            style="margin: 3px"
            v-for="(tag, idx) in pushInfo.deviceIds"
            :key="idx"
            closable
            @close="regIdDelete(idx)"
            :disable-transitions="true"
            :type="validateRegId(tag) ? '' : 'danger'"
            effect="dark"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
    </el-card>
    <el-button class="pushBtn" type="primary" @click="pushClick"
      >发送</el-button
    >
  </div>
</template>

<script>
import store from "@/store";
// 引入插件
import { swiper, swiperSlide } from "vue-awesome-swiper";
import Swiper, { Pagination, Navigation } from "swiper";
import "swiper/swiper.scss";
import "swiper/swiper-bundle.css";
import { Message } from 'element-ui'
import { getAppEnums, saveKeys } from "@/utils/enums";
import { doPushAllMsg, doPushBatchMsg } from "@/api/push"
import { copyObj } from '@/utils/util'

export default {
  name: "PushMsg",
  components: {
    swiper,
    swiperSlide,
  },
  data() {
    return {
      loading: false,
      appId: "",
      appKey: "",
      appName: "",
      // 推送平台
      basePlatform: ["安卓", "iOS开发", "iOS生产"],
      pushInfo: {
        // 推送类型 1透传消息 0 普通消息
        pushType: '0',
        // 目标平台
        platform: [],
        // 通知标题
        title: "",
        // 通知内容
        content: "",
        // 目标人群
        target: "",
        // 目标Registration ID
        deviceIds: [],
        //自定义附加字段
        extras: [],
        // 安卓配置
        androidConfig: {
          sound: ""
        },
        // iOS配置
        iosConfig: {
          sound: "default",
        },
      },
      // 当前输入的Registration ID
      registrationID: "",
      swiperOptions: {
        // loop: true,
        // autoplay: {
        //     delay: 3000,
        //     stopOnLastSlide: false,
        //     disableOnInteraction: false
        // },
        // 显示分页
        pagination: {
          el: ".swiper-pagination",
          clickable: true, //允许分页点击跳转
        },
        // 设置点击箭头
        navigation: {
          nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev",
          size: 20,
        },
      },
      currentPage: 0,
      // 安卓自定义声音提示文字
      androidSoundTip:
        "提示音（Android）</br></br>需要播放的铃声文件名，无需传递文件后缀，铃声文件放在Android工程的/res/raw目录下。</br>针对Android8.0以上，当传递了channel_id时，此属性不生效。</br>在JPush Anroid SDK 3.3.8及以后版本支持此功能。",
      // iOS自定义声音提示文字
      iOSSoundTip:
        "提示音（iOS）</br></br>默认为default，即系统默认声音。 </br>如果设置为空值，则为静音。</br>如果设置为特殊的名称，则需要你的App里配置了该声音才可以正常。",
    };
  },
  created() {
    let info = JSON.parse(sessionStorage.getItem(saveKeys().APP_INFO));
    this.appId = info.appId;
    this.appKey = info.appKey;
    this.appName = info.appName;

    // 转发内容处理
    if(this.$route.query.param != null) {
      var param = JSON.parse(this.$route.query.param)
      if(param.deviceIds.length <= 0) {
        param.target = 1
      }else {
        param.target = 4
      }
      this.pushInfo = param
      if(param.extras != null) {
        var newExtras = []
        Object.keys(param.extras).forEach(function(key) {
          let ext = {'key': key, 'value': param.extras[key]}
          newExtras.push(ext)
        })
        this.pushInfo.extras = newExtras
      }
    }
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.swiper;
    },
  },
  methods: {
    // 推送平台Change事件，由于iOS开发和iOS生产只能选一个
    platformChange(e, item) {
      if (item == "iOS开发") {
        if (e) {
          let idx = this.pushInfo.platform.findIndex(
            (str) => str === "iOS生产"
          );
          if (idx >= 0) {
            this.pushInfo.platform.splice(idx, 1);
          }
        }
      } else if (item == "iOS生产") {
        if (e) {
          let idx = this.pushInfo.platform.findIndex(
            (str) => str === "iOS开发"
          );
          if (idx >= 0) {
            this.pushInfo.platform.splice(idx, 1);
          }
        }
      }
    },
    // 浏览手机图片滑动
    handleClickSlide(index, reallyIndex) {
      console.log("Click slide!", index, reallyIndex);
    },
    // 回车输入Registration ID
    submitRegId() {
      if (this.registrationID != "") {
        this.pushInfo.deviceIds.push(this.registrationID);
        this.registrationID = "";
      }
    },
    // 删除Registration ID
    regIdDelete(index) {
      this.pushInfo.deviceIds.splice(index, 1);
    },
    // 发送浏览事件
    pushClick(e) {
      var that = this
      if(!that.validateCanSend()) {
        return
      }
      let param = copyObj({...{appKey: that.appKey}, ...that.pushInfo})
      // 处理extras，接口需要map
      var newExtras = {}
      param.extras.forEach(item => {
        newExtras[item.key] = item.value
      });
      param.extras = newExtras
      console.log('发送内容：', param)
      if(that.pushInfo.target == 1) {// 全推
        that.loading = true
        doPushAllMsg(param).then(response => {
          Message({
            message: "发送成功",
            type: 'success',
            duration: 1000
          })
          that.loading = false
        }).catch(error => {
          that.loading = false;
        })
      }else if(this.pushInfo.target == 4) {// 根据regID精准推送
        that.loading = true
        doPushBatchMsg(param).then(response => {
          Message({
            message: "发送成功",
            type: 'success',
            duration: 1000
          })
          that.loading = false
        }).catch(error => {
          that.loading = false;
        })
      }
    },
    // 添加自定义字段
    custommsgAdd() {
      var p = { key: "", value: "" };
      this.pushInfo.extras.push(p);
      console.log("custommsg:", this.pushInfo.extras);
    },
    // 减去自定义字段
    custommsgSub(index) {
      this.pushInfo.extras.splice(index, 1);
    },
    // 校验RegID，需要为11位或19位
    validateRegId(regId) {
      // 暂时不校验格式
      return true
      if(regId.length == 11) {
        return true
      }else if(regId.length == 19) {
        return true
      }
      return false
    },
    // 校验是否可以提交
    validateCanSend() {
      if(this.pushInfo.title == '') {
        Message({
          message: "请输入通知标题",
          type: 'warning',
          duration: 1000
        })
        return false
      }
      if(this.pushInfo.content == '') {
        Message({
          message: "请输入通知内容",
          type: 'warning',
          duration: 1000
        })
        return false
      }
      if(this.pushInfo.target == '') {
        Message({
          message: "请选择目标人群",
          type: 'warning',
          duration: 1000
        })
        return false
      }
      if(this.pushInfo.target == '4' && this.pushInfo.deviceIds.length <= 0) {
        Message({
          message: "请至少输入一个设备ID",
          type: 'warning',
          duration: 1000
        })
        return false
      }
      return true
    }
  },
};
</script>

<style lang="scss" scoped>
.pushmsg {
  &-container {
    display: flex;
    // align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    margin: 20px;
  }
  &-card {
    width: 100%;
    margin-bottom: 20px;
  }
  &-editView {
    width: 100%;
    display: flex;
    flex-direction: row;
    //   justify-content: center;
  }
  &-editLeft {
    width: 50%;
    margin-right: 20px;
  }
  &-previewTitleView {
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    border-bottom-style: solid;
    border-width: 1px;
    border-color: #dddee0;
  }
  &-previewTitle {
    color: #333333;
    font-size: 18px;
    margin: 10px;
    margin-bottom: 0px;
  }
  &-previewSubTitle {
    color: #646464;
    font-size: 14px;
    margin: 10px;
  }
  &-swiper {
    width: 298px;
    height: 532px;
  }
  &-pimgView {
    position: relative;
    width: 100%;
    height: 100%;
    //   display: flex;
    //   flex-direction: row;
    //   align-items: center;
    //   justify-content: center;
  }
  &-img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  &-appNameAndroid {
    position: absolute;
    line-height: 20px;
    font-size: 12px;
    font-weight: 400;
    text-align: start;
    top: 38.5%;
    left: 70px;
    width: 175px;

    white-space: nowrap; /*强制span不换行*/
    display: inline-block; /*将span当做块级元素对待*/
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
  }
  &-msgTitleAndroid {
    position: absolute;
    line-height: 20px;
    font-size: 12px;
    text-align: start;
    top: 42.3%;
    left: 48px;
    width: 195px;

    white-space: nowrap; /*强制span不换行*/
    display: inline-block; /*将span当做块级元素对待*/
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
  }
  &-msgInfoAndroid {
    position: absolute;
    line-height: 20px;
    font-size: 12px;
    text-align: start;
    top: 45.5%;
    left: 48px;
    width: 195px;

    white-space: nowrap; /*强制span不换行*/
    display: inline-block; /*将span当做块级元素对待*/
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
  }
  &-appNameiOS1 {
    position: absolute;
    line-height: 20px;
    font-size: 12px;
    font-weight: 400;
    text-align: start;
    top: 35%;
    left: 75px;
    width: 175px;

    white-space: nowrap; /*强制span不换行*/
    display: inline-block; /*将span当做块级元素对待*/
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
  }
  &-msgTitleiOS1 {
    position: absolute;
    line-height: 20px;
    font-size: 12px;
    text-align: start;
    top: 38.8%;
    left: 50px;
    width: 195px;

    white-space: nowrap; /*强制span不换行*/
    display: inline-block; /*将span当做块级元素对待*/
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
  }
  &-msgInfoiOS1 {
    position: absolute;
    line-height: 20px;
    font-size: 12px;
    text-align: start;
    top: 42%;
    left: 50px;
    width: 195px;

    white-space: nowrap; /*强制span不换行*/
    display: inline-block; /*将span当做块级元素对待*/
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
  }
  &-appNameiOS2 {
    position: absolute;
    line-height: 20px;
    font-size: 12px;
    font-weight: 400;
    text-align: start;
    top: 12.5%;
    left: 75px;
    width: 175px;

    white-space: nowrap; /*强制span不换行*/
    display: inline-block; /*将span当做块级元素对待*/
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
  }
  &-msgTitleiOS2 {
    position: absolute;
    line-height: 20px;
    font-size: 12px;
    text-align: start;
    top: 16.3%;
    left: 50px;
    width: 195px;

    white-space: nowrap; /*强制span不换行*/
    display: inline-block; /*将span当做块级元素对待*/
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
  }
  &-msgInfoiOS2 {
    position: absolute;
    line-height: 20px;
    font-size: 12px;
    text-align: start;
    top: 19.5%;
    left: 50px;
    width: 195px;

    white-space: nowrap; /*强制span不换行*/
    display: inline-block; /*将span当做块级元素对待*/
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
  }
  &-configTitle {
    color: #3b3b3b;
    font-size: 14px;
    font-weight: bold;
    background-color: #f7f7f7;
    padding: 5px;
    border-radius: 14px;
    margin-bottom: 10px;
    width: 100px;
    text-align: center;
  }
}

.recommendPage {
  position: relative;
  width: 300px;
  height: 600px;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  border-style: solid;
  border-width: 1px;
  border-color: #dddee0;
}

.recommendPage .swiper-container {
  --swiper-navigation-color: #000; /* 单独设置按钮颜色 */
  --swiper-navigation-size: 12px; /* 设置按钮大小 */
}
.recommendPage .swiper-container .swiper-slide {
  width: 100%;
  line-height: 200px;
  color: #000;
  font-size: 16px;
  text-align: center;
}

.targetIccIdInput {
  width: 60%;
  display: flex;
  flex-direction: column;
  align-items: left;
}

.pushBtn {
  width: 160px;
  height: 40px;
}

.regIdsView {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.btn-instructions {
  width: 20px;
  height: 20px;
  margin-left: 10px;
}

.btn-delete {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.row-margin {
  margin-top: 10px;
  margin-bottom: 10px;
  height: 40px;
}
.item-col {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.div-customemsg {
  display: flex;
  flex-direction: row;
  align-items: center;
}
</style>
